

import util from '@ohos.util';
const TAG = 'UdpModel'

export class Convert {

  // ArrayBuffer转16进制字符串
  static arrayBuffer2Hex(buffer):string {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('')
  }

  // static hexStrToBytes(hexstr:string):Uint8Array{
  //   let len=hexstr.length
  //   if(len %2!=0){
  //     const  byteArray = new Array<number>()
  //     for (let i = 0;i<hexstr.length;i+=2){
  //       byteArray.push(parseInt(hexstr.substring(i,i+2),16))
  //     }
  //     return new Uint8Array(byteArray)
  //
  //   }
  // }
  static unit8ArrayToString(arr:Uint8Array):string{
  let  str =''
  if (arr && arr.length>0){
    try{
      let textDecode = util.TextDecoder.create('utf-8')
      str =textDecode.decodeWithStream(arr)
    }catch (err){

    }
  }
  return str

}

  //解析ArrayBuffer
  static resolveArrayBuffer(message: ArrayBuffer): string {
    if (message instanceof ArrayBuffer) {
      let dataView = new DataView(message)
      let str = ""
      for (let i = 0;i < dataView.byteLength; ++i) {
        let dec = dataView.getUint8(i)
        let hex = dec.toString(16)
        if (hex.length == 2) {
          hex = "" + hex
        } else {
          hex = "0" + hex
        }
        if (hex !== "\n") {
          str += hex
        }
      }
      return str;
    }
  }

}

